const fs = require('fs')
const path = require('path')
const config = require('./config.js')

var blogsPath = config.BlogsPath
var outputPath = config.OutputPath


// 解析博客markdown文件的目录，并组织为一个json,存入文件
new Promise((resolve, reject) => {
    // 判断文件是否存在
    fs.exists(blogsPath, (exists) => {
      if (exists) resolve(blogsPath);
      else reject('Path does not exist');
    })

    fs.access(blogsPath, fs.constants.F_OK, (err) => {
      if (err == undefined) resolve(blogsPath);
      else reject('Path does not exist');
    })
  })
  .then(path => {
    var rslt = [];
    return getFiles(path).then(files => {
      return buildJson(path, files, rslt).then(value => {
        return value;
      })
    })
  })
  .then(files => {
    // 输出到配置文件
    var out = path.normalize(outputPath + '/catalog.json')
    fs.writeFile(out, JSON.stringify(files), (e) => {
      console.log(e);
    })
  })
  .catch(e => {
    console.log(e);
  })


function buildJson(path, files, rsltArray) {
  var waitingtask = 0;
  var index = 0;
  return new Promise((resolve, reject) => {
    if (files.length === 0) return tryResolve(rsltArray);
    files.forEach((value) => {
      isDirectory(path + "/" + value).then(isDir => {
        if (isDir) {
          index++;
          waitingtask++;

          var tempObj = {};
          tempObj[value] = [];
          rsltArray.push(tempObj);

          getFiles(path + "/" + value)
            .then(files => buildJson(path + "/" + value, files, tempObj[value]))
            .then(() => {
              waitingtask--;
              tryResolve();
            })
        } else {
          index++;

          if (value.endsWith('.md') || value.endsWith('.MD')) {
            rsltArray.push(value);
          }
          tryResolve();
        }
      })
    })

    function tryResolve() {
      if (waitingtask == 0 && index === files.length) {
        resolve(rsltArray);
      }
    }
  })
}

function getFiles(_path) {
  return new Promise((resolve, reject) => {
    fs.readdir(_path, (err, files) => {
      resolve(files);
    })
  })
}

function isDirectory(_path) {
  return new Promise((resolve, reject) => {
    fs.stat(_path, (e, stats) => {
      if (stats.isDirectory()) {
        resolve(true);
      } else {
        resolve(false);
      }
    })
  })
}
